package com.hskn.hss.utils;

import cn.hutool.core.date.DateUtil;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String工具类
 *
 * @author hskn
 * @email h@iaiot.com
 */
public class StringUtils {

    /**
     * 对象值非空判断,判断输入对象是否是空值
     *
     * @param obj
     * @return
     */
    public static boolean isNotEmpty(Object obj) {
        if (obj == null) {
            return false;
        }
        return !"".equals(String.valueOf(obj).trim());
    }

    /**
     * 对象值非空判断,判断输入对象是否是空值
     *
     * @param obj
     * @return
     */
    public static boolean isEmpty(Object obj) {
        return !isNotEmpty(obj);
    }

    /**
     * 手机号验证
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        String regExp = "^[1][0-9][0-9]{9}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(mobile);
        return m.matches();
    }

    /**
     * 邮箱验证
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String regExp = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(email);
        return m.matches();
    }

    /**
     * 生成随机字符串
     *
     * @param length 需要生成字符串的位数
     * @return
     */
    public static String getRandomString(int length) {
        //定义一个字符串（A-Z,a-z,0-9）共62位
        String str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取随机中文字符串
     *
     * @param length 位数
     * @return
     */
    public static String getRandomChinese(int length) {
        String str = "";
        int highPos, lowPos;
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            highPos = (176 + Math.abs(random.nextInt(71)));//区码，0xA0打头，从第16区开始，即0xB0=11*16=176,16~55一级汉字，56~87二级汉字
            random = new Random();
            lowPos = 161 + Math.abs(random.nextInt(94));//位码，0xA0打头，范围第1~94列

            byte[] bArr = new byte[2];
            bArr[0] = (new Integer(highPos)).byteValue();
            bArr[1] = (new Integer(lowPos)).byteValue();
            try {
                str += new String(bArr, "GB2312");   //区位码组合成汉字
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return str;
    }

    /**
     * 生成6位数验证码
     *
     * @return String
     */
    public static String randomCode() {
        StringBuilder str = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            str.append(random.nextInt(10));
        }
        return str.toString();
    }

    /**
     * int转BigDecimal
     *
     * @return String
     */
    public static BigDecimal bigDecimalByInt(int num) {
        return new BigDecimal(String.valueOf(num));
    }

    /**
     * 生成 uuid
     *
     * @return String
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    /**
     * 时间戳转时间
     *
     * @param ts ts
     * @return date
     */
    public static String tsToDate(long ts) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(ts);
        return date;
    }

    /**
     * String 转时间
     *
     * @param date
     * @return resdate
     */
    public static Date StringToDate(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date resdate = format.parse(date);
        return resdate;
    }

    public static Date dealDateFormat(String oldDateStr) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
        try {
            Date date = df.parse(oldDateStr);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new Date();
    }

    public static String DateFormat(Date dateparam) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = df.format(dateparam);
        return date;
    }

    public static Date StringToDate2(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date resdate = format.parse(date);
        return resdate;
    }

    public static Date StringToDate3(String date) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date resdate = format.parse(date);
        return resdate;
    }

    /**
     * LocalTime 转 string
     *
     * @param time time
     * @return hh:mm
     */
    public static String localtimeToStr(LocalTime time) {
        if (StringUtils.isNotEmpty(time)) {
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("HH:mm");
            return time.format(dtf2);
        }
        return null;
    }

    public static LocalTime dateToLocalDateTime(Date date) {
        if (StringUtils.isNotEmpty(date)) {
            Instant instant = date.toInstant();
            ZoneId zone = ZoneId.systemDefault();
            LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
            LocalTime localTime = localDateTime.toLocalTime();
            return localTime;
        }
        return null;
    }

    /**
     * LocalDate 转 string
     *
     * @param date date
     * @return yyyy-MM-dd
     */
    public static String localDateToStr(LocalDate date) {
        if (StringUtils.isNotEmpty(date)) {
            DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            return date.format(dtf2);
        }
        return null;
    }

    /**
     * Date 转 string
     *
     * @param date   date
     * @param format format
     * @return format
     */
    public static String dateToStr(Date date, String format) {
        if (StringUtils.isNotEmpty(date)) {
            SimpleDateFormat dtf2 = new SimpleDateFormat(StringUtils.isEmpty(format) ? "yyyy-MM-dd" : format);
            return dtf2.format(date);
        }
        return null;
    }

    /**
     * 用时间获取流水号
     */
    public static String Serialnumber() {
        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return String.valueOf(System.currentTimeMillis());
    }

    public static String getNo() {
        return Serialnumber() + "-" + randomCode();
    }

    public static String s2date(Long second) {
        String str = second + "秒";
        try {
            long day1 = second / (24 * 3600);
            long hour1 = second % (24 * 3600) / 3600;
            long minute1 = second % 3600 / 60;
            long second1 = second % 60;
            if (day1 != 0) {
                str = day1 + "天" + hour1 + "小时" + minute1 + "分" + second1 + "秒";
            } else if (hour1 != 0) {
                str = hour1 + "小时" + minute1 + "分" + second1 + "秒";
            } else if (minute1 != 0) {
                str = minute1 + "分" + second1 + "秒";
            } else {
                str = second1 + "秒";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }

    public static String subDate(Date date) {
        Long second = (new Date().getTime() - date.getTime()) / 1000;
        return s2date(second);
    }

    /**
     * 获取距离当前时间的秒数差
     *
     * @param start
     * @return
     */
    public static Long getTimeDifference(Date start) {
        Date nowDate = new Date();
        long time = (nowDate.getTime() - start.getTime()) / 1000;
        return time;
    }

    /**
     * Description: 判断一个时间是否在一个时间段内 </br>
     *
     * @param nowTime   当前时间 </br>
     * @param beginTime 开始时间 </br>
     * @param endTime   结束时间 </br>
     */
    private boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        return date.after(begin) && date.before(end);
    }

    public static java.sql.Date formatData(Date date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strDate = sdf.format(date);//格式化成yyyy-MM-dd格式的时间字符串
        Date newDate = sdf.parse(strDate);//将字符串转换为时间格式
        return new java.sql.Date(newDate.getTime());
    }

    //EEE MMM dd HH:mm:ss zzz yyyy 转为 yyyy-MM-dd HH:mm:ss
    public static String FormatData(Date date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date date1 = sdf.parse(date.toString());
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date1);
    }

    //EEE MMM dd HH:mm:ss zzz yyyy 转为 yyyy-MM-dd HH:mm:ss
    public static String FormatDataDay(Date date) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);
        Date date1 = sdf.parse(date.toString());
        return new SimpleDateFormat("yyyy-MM-dd").format(date1);
    }

    //计算两个时间的秒数
    public static int calLastedTime(Date startDate, Date endDate) {
        long a = endDate.getTime();
        long b = startDate.getTime();
        int c = (int) ((a - b) / 1000);
        return c;
    }

    /**
     * 判断当前时间距离第二天凌晨的秒数
     *
     * @return 返回值单位为[s:秒]
     */
    public static Long getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

    /**
     * 获取当天凌晨的时间
     *
     * @return
     */
    public static Date getZeroHourToday(){
        SimpleDateFormat sdfYMD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0); //这是将当天的【秒】设置为0
        calendar.set(Calendar.MINUTE, 0); //这是将当天的【分】设置为0
        calendar.set(Calendar.HOUR_OF_DAY, 0); //这是将当天的【时】设置为0
        String ymd = sdfYMD.format(calendar.getTime());
        return DateUtil.parseDateTime(ymd);
    }

    /**
     * 获取当天最后的时间
     *
     * @return
     */
    public static Date getLastHourToday(){
        SimpleDateFormat sdfYMD = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 59); //这是将当天的【秒】设置为0
        calendar.set(Calendar.MINUTE, 59); //这是将当天的【分】设置为0
        calendar.set(Calendar.HOUR_OF_DAY, 23); //这是将当天的【时】设置为0
        String ymd = sdfYMD.format(calendar.getTime());
        return DateUtil.parseDateTime(ymd);
    }

    /**
     * 根据时分拼接完整时间
     *
     * @return
     */
    public static Date getAllDate(Date date, String time) throws ParseException {
        Date shiftStartDate = StringUtils.StringToDate(StringUtils.dateToStr(date, "") + " " + time + ":00");
        return shiftStartDate;
    }

    /**
     * 获取当月第一天
     *
     * @return
     */
    public static String firstDayByMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        String first = format.format(c.getTime());
        return first;
    }

    /**
     * 获取当月最后一天
     *
     * @return
     */
    public static String lastDayByMonth() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月最后一天
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        String last = format.format(ca.getTime());
        return last;
    }

    /**
     * 获取某年第一天日期开始时刻
     * @return Date
     */
    public static Date getYearFirstDay(){
        Calendar cal = Calendar.getInstance();
        //获取当前年份
        int year = cal.get(Calendar.YEAR);
        cal.clear();
        cal.set(Calendar.YEAR, year);
        Date yearFirstDay = cal.getTime();
        return getStartDate(yearFirstDay);
    }

    /**
     * 得到指定日期的一天的开始时刻00:00:00
     *
     * @param date
     * @return
     */
    public static Date getStartDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat format1 = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");

        String temp = format.format(date);
        temp += " 00:00:00";

        try {
            return format1.parse(temp);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @param lo 毫秒数
     * @return String yyyy-MM-dd HH:mm:ss
     * @Description: long类型转换成日期
     */

    public static String longToDate(long lo) {
        Date date = new Date(lo);
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sd.format(date);
    }
}
